package xm.chengdu.com.sbglxt;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import Thread.BluetoothCommunicateThread;
import de.greenrobot.event.EventBus;
import utils.EncodingUtil;
import utils.SpfUtils;

public class MainActivity extends Activity implements OnClickListener {
    ProgressDialog dialog = null;
    public static BluetoothAdapter btAdapter = BluetoothAdapter
            .getDefaultAdapter();
    // 所有配置文件名称
    public static Map<String, String> map = new HashMap<String, String>();
    public static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    public static BluetoothSocket btSocket = null;
    // public static BluetoothConnectThread btConnThread = null;
    public static BluetoothCommunicateThread btCommThread;
    Button button1;
    Button button2, button3;
    TextView tv_ts, tv_ts2, textView1;

    OutputStream outputStream;

    static {
        map.put("Mac", "0");
        map.put("Mac", "0");
        map.put("PsamNumForVersion1", "1");
    }

    Handler handler = new Handler(new Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();

                    button2.setEnabled(false);
                    button3.setVisibility(View.VISIBLE);
                    dialog.dismiss();
                    textView1.setText("已连接");
                    startActivity(new Intent(MainActivity.this, Success_Activity.class));
                    break;
                case 2:
                    Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                    button2.setEnabled(true);
                    break;
                case 3:


                    String str3 = (String) msg.obj;
                    Toast.makeText(MainActivity.this, str3, Toast.LENGTH_SHORT).show();



                    MyEvent events = new MyEvent();
                    events.setType("mingling");
                    events.setContent(str3);
                    EventBus.getDefault().post(events);


                    break;


                default:
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);

        BluetoothCommunicateThread.isRun = false;
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);
        tv_ts = (TextView) findViewById(R.id.tv_ts);
        tv_ts2 = (TextView) findViewById(R.id.tv_ts2);
        textView1 = (TextView) findViewById(R.id.textView1);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                duankai();

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void lianjie() {
        if (BluetoothCommunicateThread.isRun) {
            Toast.makeText(MainActivity.this, "已连接上蓝牙设备", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // Log.e("77", "88未连接");
            openView();
            new Thread() {
                @Override
                public void run() {
                    try {
                        if (btAdapter.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
                            throw new NumberFormatException("蓝牙设备未开启");
                        }
                        String address = (String) SpfUtils.get(
                                MainActivity.this, "address", "");
                        if (address.equals("")) {
                            throw new NumberFormatException("没有配对的蓝牙设备");
                        }
                        BluetoothDevice btDevice = btAdapter
                                .getRemoteDevice(address);
                        if (btDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
                            connect(btDevice);
                        } else {
                            throw new NumberFormatException("与蓝牙设备未配对");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Message msg = new Message();
                        msg.what = 2;
                        handler.sendMessage(msg);
                        Log.e("777", "连接抛异常");
                    }
                }

            }.start();

        }

    }

    public void connect(BluetoothDevice btDevice) {
        UUID uuid = UUID.fromString(SPP_UUID);
        try {
            Log.d("666", "connect()");
            btSocket = btDevice.createRfcommSocketToServiceRecord(uuid);
            btSocket.connect();
            Message msg = new Message();
            msg.what = 1;
            handler.sendMessage(msg);
            startComm();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("777", "连接中抛异常！");
            try {
                btSocket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            Message msg = new Message();
            msg.what = 2;
            handler.sendMessage(msg);
        }
    }

    public void startComm() {
        btCommThread = new BluetoothCommunicateThread(handler, btSocket,
                MainActivity.this);
        btCommThread.isRun = true;
        btCommThread.start();

    }

    // 显示连接窗口
    public void openView() {
        dialog = new ProgressDialog(MainActivity.this);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setTitle("处理中........");
        dialog.setMessage("请稍后........");
        dialog.show();
        dialog.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface d, int keyCode, KeyEvent event) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_HOME:
                        if (dialog != null) {
                            dialog.dismiss();
                            dialog = null;
                        }
                        return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                startActivity(new Intent(MainActivity.this, PD_Activity.class));
                break;
            case R.id.button2:
                lianjie();
//                String getmac = getmac("01");
//                Log.e("888", getmac);
                break;
            default:
                break;
        }

    }

    public String getmac(String name) {
        String tou = "55AA";
        String dzt = "01";
        String len = "";
        String data = "";
        String BCC = "";
//		Log.e("722", "722" + name);
//		Log.e("722", "722" + name.length());
        data = strToHex(name);
//		Log.e("722", "722" + data);
        len = EncodingUtil.desToHex(data.length() / 2, 4);
        String DATA = dzt + len + "B1" + data;// date
        BCC = EncodingUtil.yihuo(EncodingUtil.change(DATA));
        return tou + dzt + len + "B1" + data + BCC;
    }

    public static String strToHex(String target) {
        String codeType = "gbk";
        byte[] bytes = target.getBytes(Charset.forName(codeType));
        String s = "";
        for (int i = 0; i < bytes.length; i++) {
            s += Integer.toHexString(bytes[i] & 0xFF);
        }
        return s;
    }

    boolean isConn;

    public void duankai() {
        if (btSocket.isConnected()) {
            try {
                btSocket.close();
                isConn = false;
                Log.i("BluetoothUtil", "stopConn");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            isConn = false;
        }

        if (!isConn) {
            button3.setVisibility(View.INVISIBLE);
            button2.setEnabled(true);
            Toast.makeText(MainActivity.this, "蓝牙断开成功！", Toast.LENGTH_SHORT).show();
            textView1.setText("未连接");
            tv_ts.setText(" ");
            tv_ts2.setText(" ");
            BluetoothCommunicateThread.isRun = false;
        } else {
            Toast.makeText(MainActivity.this, "蓝牙断开失败！", Toast.LENGTH_SHORT).show();
        }

    }

    public void fasong(String st) {
        btCommThread.SendStr(st);
    }

    public void onEventMainThread(MyEvent event) {

        if (!TextUtils.isEmpty(event.getType())) {
            if (event.getType().equals("message")) {

                fasong(event.getContent());


            }


        }
    }

}
